<template>
  <div class="dynamic-workflow">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="120px"
      class="workflow-form"
    >
      <template v-for="group in template.layout.groups" :key="group.id">
        <el-card v-if="group.visible" class="param-group">
          <template #header>
            <div class="group-header">
              <span>{{ group.title }}</span>
            </div>
          </template>

          <template v-for="paramId in group.params" :key="paramId">
            <el-form-item
              v-if="getParam(paramId)?.visible"
              :label="getParam(paramId)?.label"
              :prop="paramId"
            >
              <!-- 文本输入 -->
              <el-input
                v-if="getParam(paramId)?.type === 'text'"
                v-model="formData[paramId]"
                :placeholder="getParam(paramId)?.placeholder"
              />

              <!-- 数字输入 -->
              <el-input-number
                v-else-if="getParam(paramId)?.type === 'number'"
                v-model="formData[paramId]"
                :min="getParam(paramId)?.min"
                :max="getParam(paramId)?.max"
                :step="getParam(paramId)?.step"
              />

              <!-- 选择器 -->
              <el-select
                v-else-if="getParam(paramId)?.type === 'select'"
                v-model="formData[paramId]"
                :placeholder="getParam(paramId)?.placeholder"
              >
                <el-option
                  v-for="option in getParam(paramId)?.options"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                />
              </el-select>

              <!-- 图片上传 -->
              <upload-field
                v-else-if="getParam(paramId)?.type === 'image'"
                v-model="formData[paramId]"
                accept="image/*"
              />

              <!-- 开关 -->
              <el-switch
                v-else-if="getParam(paramId)?.type === 'switch'"
                v-model="formData[paramId]"
              />

              <!-- 滑块 -->
              <el-slider
                v-else-if="getParam(paramId)?.type === 'slider'"
                v-model="formData[paramId]"
                :min="getParam(paramId)?.min"
                :max="getParam(paramId)?.max"
                :step="getParam(paramId)?.step"
              />
            </el-form-item>
          </template>
        </el-card>
      </template>

      <!-- 操作按钮 -->
      <div class="form-actions">
        <el-button
          type="primary"
          :loading="executing"
          @click="execute"
        >
          执行
        </el-button>
        <el-button @click="reset">重置</el-button>
      </div>
    </el-form>

    <!-- 执行结果对话框 -->
    <el-dialog
      v-model="resultDialog.visible"
      :title="resultDialog.status === 'success' ? '执行成功' : '执行失败'"
      width="50%"
    >
      <div class="result-content">
        <template v-if="resultDialog.status === 'success'">
          <div v-if="resultDialog.images?.length" class="result-images">
            <el-image
              v-for="(image, index) in resultDialog.images"
              :key="index"
              :src="image"
              :preview-src-list="resultDialog.images"
              fit="cover"
            />
          </div>
        </template>
        <template v-else>
          <p class="error-message">{{ resultDialog.error }}</p>
        </template>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { useWorkflowStore } from '@/stores/workflow'
import UploadField from './UploadField.vue'
import type { WorkflowTemplate, WorkflowParam } from '@/types/workflow'

const props = defineProps<{
  template: WorkflowTemplate
}>()

const workflowStore = useWorkflowStore()

const formRef = ref<FormInstance>()
const executing = ref(false)

// 表单数据
const formData = reactive<Record<string, any>>({})

// 初始化表单数据
const initFormData = () => {
  props.template.params.forEach(param => {
    formData[param.id] = param.default
  })
}

// 获取参数配置
const getParam = (id: string): WorkflowParam | undefined => {
  return props.template.params.find(param => param.id === id)
}

// 表单验证规则
const rules = computed<FormRules>(() => {
  const rules: FormRules = {}
  props.template.params.forEach(param => {
    if (param.required) {
      rules[param.id] = [{
        required: true,
        message: `请输入${param.label}`,
        trigger: param.type === 'image' ? 'change' : 'blur'
      }]
    }
  })
  return rules
})

// 结果对话框
const resultDialog = reactive({
  visible: false,
  status: 'success' as 'success' | 'error',
  images: [] as string[],
  error: ''
})

// 执行工作流
const execute = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    
    executing.value = true
    const result = await workflowStore.executeWorkflow(props.template.id, formData)
    
    resultDialog.visible = true
    resultDialog.status = 'success'
    resultDialog.images = result.images || []
    resultDialog.error = ''
  } catch (error: any) {
    resultDialog.visible = true
    resultDialog.status = 'error'
    resultDialog.images = []
    resultDialog.error = error.message || '执行失败'
  } finally {
    executing.value = false
  }
}

// 重置表单
const reset = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  initFormData()
}

// 初始化
initFormData()
</script>

<style scoped lang="scss">
.dynamic-workflow {
  .workflow-form {
    .param-group {
      margin-bottom: 24px;

      .group-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
    }
  }

  .form-actions {
    margin-top: 24px;
    text-align: center;
  }

  .result-content {
    .result-images {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
      gap: 16px;

      .el-image {
        width: 100%;
        height: 200px;
        border-radius: 4px;
        overflow: hidden;
      }
    }

    .error-message {
      color: var(--el-color-danger);
      text-align: center;
    }
  }
}
</style> 